var pageNum = 0;
var drawLocked = false;
var docObject;
var wisId = "";
var userid = "";
var userName = "";
var classid = "";
var topic_msg = "";
var topic_stu_to_teacher = "";
var topic_teacher_to_stu = "";
var topic_stu_to_stu = "";
var online_count = 0;
var handerStuid = "";
var handerStuname = "";
var dmsPubKey = "";
var dmsSubKey = "";
var rtmp_publish_url = "";
var rtmp_play_url = "";
var hls_play_url = "";
var lssapp_id = "";
var stream_tea = "";
//var stream_stu = "";
var lss;
var play_status = 0;
var hand_status = 0;
var objectPlayer;

function GetQueryString(param) {
	var request = {
		QueryString : function(val) {
			var uri = window.location.search;
			var re = new RegExp("" + val + "=([^&?]*)", "ig");
			return ((uri.match(re)) ? (decodeURI(uri.match(re)[0]
					.substr(val.length + 1))) : '');
		}
	};
	return request.QueryString(param);
}

/*
 * 初始化参数
 */
function initParam() {
	wisId = GetQueryString("wisid");
	userid = GetQueryString("userid");
	userName = GetQueryString("name");
	classid = GetQueryString("classid");
	topic_msg = GetQueryString("topic");
	topic_stu_to_teacher = GetQueryString("topic") + "_to_teacher";
	topic_teacher_to_stu = GetQueryString("topic") + "_to_stu";
	topic_stu_to_stu = GetQueryString("topic") + "_stu_to_stu";
	lssapp_id = GetQueryString("lssapp_id");
    stream_tea = GetQueryString("stream_tea");
    //stream_stu = GetQueryString("stream_stu");
	if (userName == null || userName.length == 0)
		userName = "匿名";
}

function initUrl(data){
	rtmp_publish_url = data.rtmp_publish_url;
	rtmp_play_url = data.rtmp_play_url;
	hls_play_url = data.hls_play_url;
	dmsPubKey = data.dmsPubKey;
	dmsSubKey = data.dmsSubKey;
}

function u_c(c,u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'u_c',
			classid : c,
			userid : u
		},
		success : function(data) {
			if (data.Flag == 100) {
				if(data.Info && data.Info.result){
					initUrl(data);
					initWis();
					initDms();
					initTool();
					initPlay();
				}else{
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error : function(error){
			window.location.href = "apierror2.html";
			return;
		}
	});
}

function u_c_c(c,u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'u_c',
			classid : c,
			userid : u
		},
		success : function(data) {
			if (data.Flag == 100) {
				if(data.Info && data.Info.result){
					
				}else{
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error : function(error){
			window.location.href = "apierror2.html";
			return;
		}
	});
}

/**
 * 初始化白板
 */
function initWis() {
	var api = WISAPI.New('./interface.php');
	WIS.Init({
		wisId : wisId,
		api : api,
		userid_ : userid,
		container : 'wis_context_inner',
		width : 0,
		height : 0,
		success : function() {
			WIS.Color("#FF8C00");
			WIS.AllowDraw({
				ballow : false
			});

		},
		failure : function(err) {
			console.log("init fail:  " + JSON.stringify(err));
			alert("加载课件文档失败，请刷新页面重新加载");
		},
		updateUser : function(total,data_) {
			$(".rightLabel span").html(total);
			online_count = total;
			if (data_.state == 0) {
				handleStuout(data_.clientId);
			}
		},
		onConnect : function() {
		},
		onReconnect : function() {
			
		},
		onConnectClose : function() {
			
		},
		onDocLoad : function(info) {
			console.log("docObject:" + JSON.stringify(info));
			docObject = info;
			if (!!docObject) {
				$("#docList div[docId=" + docObject["id"] + "]").addClass(
						"selectDoc");
				$("#docList div[docId=" + docObject["id"] + "]").siblings()
						.removeClass("selectDoc");
			}
		},
		onPageChange : function(page, total) {
			pageNum = total;
			$("#pageList").html("");
			for (var i = 1; i <= total; i++) {
				var option = $("<option>").val(i).text(i);
				$("#pageList").append(option);
			}
			$("#pageList").val(page);
		}
	});
}


/** **************DMS相关**************** */
function AddMessage(name, msg, style) {
	var faceMsg = msg;
	for ( var item in faceMap) {
		faceMsg = faceMsg.replace(new RegExp("\\" + item, "g"),
				"<img src='images/faces/" + faceMap[item] + ".gif'/>");
	}
	var msgHtml = "<div><span class='" + style + "' >" + name + "：</span>"
			+ faceMsg + "</div>";
	$("#messageBox").html($("#messageBox").html() + msgHtml);
	$("#messageBox").scrollTop(
			document.getElementById("messageBox").scrollHeight);
}

function Publish() {
	var send = $("#msgSendTxt").val();
	if (send == "")
		return;
	send = jQuery('<div />').text(send).html();
	ROP.Publish('{  "name":"' + userName + '", "message": "' + send + '"}',
			topic_msg);
	$("#msgSendTxt").val("");
}

function initDms() {
	ROP.On("enter_suc", function() {
		AddMessage("系统消息", "连接成功", "sysSpan");
		pubStuEnterMsg();
	});
	ROP.On("reconnect", function() {
		AddMessage("系统消息", "重新连接", "sysSpan");
	});
	ROP.On("offline", function(err) {
		AddMessage("系统消息", "连接已断开", "sysSpan");
		window.location.href = "doulogin.html";
		return;
	});
	ROP.On("enter_fail", function(err) {
		AddMessage("系统消息", "连接失败", "sysSpan");
	});
	ROP.On("losed", function() {
		AddMessage("系统消息", "连接已丢失", "sysSpan");
	});
	ROP.On("publish_data", function(data, topic) {
		var d = eval('(' + data + ')');
		if (topic == topic_msg) {
			var msg = d["message"];
			if (msg != null) {
				AddMessage((!!d["name"]) ? d["name"] : "匿名", msg);
			}
		}
		
		if(topic == topic_teacher_to_stu){
			handleCtrlMsg(d);
	    }
		
		if(topic == topic_stu_to_stu){
			handleStuMsg(d);
		}

	});
	
	ROP.Enter(dmsPubKey, dmsSubKey,classid+"_"+userid);
	ROP.Subscribe(topic_msg);
	ROP.Subscribe(topic_teacher_to_stu);
	ROP.Subscribe(topic_stu_to_stu);
	document.onkeydown = function(e) {
		if (e == null || e.keyCode == null || e.ctrlKey == null)
			return;
		if (e.keyCode == 13 && e.ctrlKey) {
			document.getElementById("msgSendTxt").value += "\n";
		} else if (e.keyCode == 13) {
			e.preventDefault();
			Publish();
		}
	};
}

var getCount = 0;
function pubStuEnterMsg(){
	if(getCount>10){
		return;
	}
	if(!WIS.getClientid()){
		getCount++;
		setTimeout(function(){
			pubStuEnterMsg();
		},500);
		return;
	}
    ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","clientid":"'+WIS.getClientid()+'","oper":"enter"}', topic_stu_to_teacher);
    ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","clientid":"'+WIS.getClientid()+'","oper":"enter"}', topic_stu_to_stu);
    ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","clientid":"'+WIS.getClientid()+'","oper":"refresh"}', topic_stu_to_stu);
    return;
}

function callbackplay(){
	jwplayer(player).play(true);
}
var position = -1;
function callbackseek(){
	if(position != -1){
		jwplayer(player).seek(parseInt(position));
		position = -1;
	}
}

function handleStuout(clientid) {
	$(".stuView").each(function(index, element) {
		var clientid_ = $(this).attr("clientid");
		if (clientid == clientid_) {
			$(this).remove();
			return;
		}
	});
}

function handleCtrlMsg(ctrlMsg) {
	if(ctrlMsg['oper'] == 'refresh'){
		ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","clientid":"'+WIS.getClientid() +'","oper":"enter"}', topic_stu_to_teacher);
	}
	if(ctrlMsg['oper'] == 'mute'){
		if(ctrlMsg["userid"] == userid)
			$(window.parent.document).contents().find("#publishframe")[0].contentWindow.muteme();
	}
	if(ctrlMsg['oper'] == 'nomute'){
		if(ctrlMsg["userid"] == userid)
			$(window.parent.document).contents().find("#publishframe")[0].contentWindow.nomuteme();
	}
	if(ctrlMsg['oper'] == 'muteall'){
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.muteme();
	}
	if(ctrlMsg['oper'] == 'nomuteall'){
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.nomuteme();
	}
	if(ctrlMsg["oper"] == "loadmp3"){
		var file = ctrlMsg["file"];
		loadMp3Player(file,null,null);
	}
	if(ctrlMsg["oper"] == "mp3play"){
		var file = ctrlMsg["file"];
		position = ctrlMsg["position"];
		if(!jwplayer(player).getPlaylist() || jwplayer(player).getPlaylist() < 1){
			loadMp3Player(file,callbackplay,callbackseek);
			return;
		}
		var curfile = jwplayer(player).getPlaylistItem(0).file;
		if(curfile != file){
			loadMp3Player(file,callbackplay,callbackseek);
		}else{
			jwplayer(player).play(true);
			position = -1;
		}
	}
	if(ctrlMsg["oper"] == "mp3pause"){
		jwplayer(player).pause(true);
	}
	if(ctrlMsg["oper"] == "mp3mute"){
		jwplayer(player).setMute(ctrlMsg["mute"]);
	}
	if(ctrlMsg["oper"] == "mp3seek"){
		console.log("offset:"+ctrlMsg["offset"]);
		jwplayer(player).seek(parseInt(ctrlMsg["offset"]));
	}
}

function handleStuMsg(stuMsg){
	if(stuMsg["oper"] == "refresh"){
		if(stuMsg["userid"] != userid){
			ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","clientid":"'+WIS.getClientid() +'","oper":"enter"}', topic_stu_to_stu);
		}
	}
	if(stuMsg["oper"] == "enter"){
		var vadioHtml = "";
		if(stuMsg["userid"] == userid){
			//开启publish
			vadioHtml = '<div stuId="'+stuMsg["userid"]+'" clientid="'+stuMsg["clientid"]+'" class="stuView">'
	          + '    <div class="displayBox">'
	          + '        <iframe id="publishframe" allowtransparency="true" frameBorder="0" scrolling="no" width="278px" height="180px" src="stu_publish.html?lssapp_id=' + lssapp_id + '&stream_stu=stream_'+ stuMsg["userid"] +'" ></iframe>'
	          + '    </div>'
	          + '    <div class="displayCtrlBar">'
	          + '        <a id="stupublish" class="offMicBtn" onclick="publishme()">上麦</a>'
	          + '        <a id="stupubset" class="offMicBtn" onclick="stupubset()">设</a>'
	          + '        <span>'+stuMsg["name"]+'视频</span>'
	          + '    </div>'
	          + '</div>';
		}else{
			//开启play
			vadioHtml = '<div stuId="'+stuMsg["userid"]+'" clientid="'+stuMsg["clientid"]+'" class="stuView">'
	          + '    <div class="displayBox">'
	          + '        <iframe allowtransparency="true" frameBorder="0" scrolling="no" width="278px" height="180px" src="stu_play.html?lssapp_id=' + lssapp_id + '&stream_stu=stream_'+ stuMsg["userid"] +'" ></iframe>'
	          + '    </div>'
	          + '    <div class="displayCtrlBar">'
	          + '        <span>'+stuMsg["name"]+'视频</span>'
	          + '    </div>'
	          + '</div>';
		}
		var flag = false;
		$(".stuView").each(function(index,ele){
			var clientid_ = $(this).attr("clientid");
			if (stuMsg["clientid"] == clientid_) {
				flag = true;
				return false;
			}
		});
		if(!flag){
			$(".stuView_vadio").append(vadioHtml);
		}
	}
}

function canvasSupport() {
	return !!document.createElement('canvas').getContext;
}

function publishme(){
	var opername = $("#stupublish").html();
	if(opername == "上麦"){
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.publishme();
		$("#stupublish").html("下麦");
		$("#stupubset").hide();
	}else{
		$("#stupublish").html("上麦");
		$("#stupubset").show();
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.closeme();
	}
	
}

//收起或展开
var stuview_status = 1;//展开
function colexpme(){
	if(stuview_status == 1){//收起操作
		$(".stuView_all .stuView_vadio").animate({height: 'toggle', opacity: 'toggle'}, "slow");
		$("#order_oper").hide();
		$(".stuView_all").animate({width:"80px"},500);
		$("#colexp_oper").html("展开");
		stuview_status = 0;
	}else{
		$(".stuView_all .stuView_vadio").animate({height: 'toggle', opacity: 'toggle'}, "slow");
		if(order_status == 1)
			$(".stuView_all").animate({width:"585px"},500);
		else
			$(".stuView_all").animate({width:"288px"},500);
		$("#order_oper").show();
		$("#colexp_oper").html("收起");
		stuview_status = 1;
	}
}
//横排竖排
var order_status = 0;//竖排
function orderme(){
	if(order_status == 1){//转为竖排
		$(".stuView_all").animate({width:"288px"},500);
		$("#order_oper").html("横排");
		order_status = 0;
	}else{
		$(".stuView_all").animate({width:"585px"},500);
		$("#order_oper").html("竖排");
		order_status = 1;
	}
}

function stupubset(){
	var stuframe = $(window.parent.document).contents().find("#publishframe")[0].contentWindow;
	var micArray = stuframe.getMics();
	var camArray = stuframe.getCams();
	if(!micArray || !camArray){
		alert("暂未获取到设备，请稍后设置");
		return;
	}
	$("#selmic option").remove();
	$("#selcam option").remove();
	var selmic = stuframe.getStumic();
	var selcam = stuframe.getStucam();
	for(var i=0;i<5;i++){
		if(micArray[i]){
			if(i == selmic){
				$("#selmic").append("<option value="+i+" selected>"+micArray[i]+"</option>");
			}else{
				$("#selmic").append("<option value="+i+">"+micArray[i]+"</option>");
			} 
		}
		if(camArray[i]){
			if(i == selcam){
				$("#selcam").append("<option value="+i+" selected>"+camArray[i]+"</option>");
			}else{
				$("#selcam").append("<option value="+i+">"+camArray[i]+"</option>");
			}
		}
	}
	$('#mysetModal').reveal();
}

function initTool() {
	$(".toolList .toolItem").live("click", function() {
		if($(this).attr("id") == "largeTool"){
			var cur_width = $("#wis_context").width();
			var des_width = cur_width + 50;
			var screenwidth = window.screen.width;
			var limitwidth = screenwidth -76 - 10 - 280;
			if(des_width > limitwidth) return;
			WIS.Resize(des_width,0);
		}else if($(this).attr("id") == "smallTool"){
			var cur_width = $("#wis_context").width();
			var des_width = cur_width - 50;
			if(des_width < 300) return;
			WIS.Resize(des_width,0);
		}
	});
	
}

function genK(option) {
	if (!classid) {
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'genK',
			appid : option.appid,
			stream : option.stream
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error : option.failure
	});
}

function initPlay(){
	var stream_tea_tmp = stream_tea.replace(/-/g,'_');
	genK({
		appid : lssapp_id,
		stream : stream_tea_tmp,
		success : function(data) {
			console.log(data);
			objectPlayer = new aodianPlayer({
				container : 'playerView',
				rtmpUrl : rtmp_play_url + '/' + lssapp_id + '/' + stream_tea_tmp + '?k=' + data.k + '&t=' + data.t,
				hlsUrl : hls_play_url + '/' + lssapp_id + '/' + stream_tea_tmp + '.m3u8' + '?k=' + data.k + '&t=' + data.t,
				name : 'jwplayer',
				width : '278',
				height : '180',
				autostart : true,
				bufferlength : '1',
				maxbufferlength : '2',
				stretching : '1',
				controlbardisplay : 'disable',
				adveDeAddr:'images/yt_02.png',
		        adveWidth:278,
		        adveHeight:130,
		        adveReAddr:'http://www.ykyueke.com'
			});
			
		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
		
	if(!canvasSupport()){
    	$(".switchBtn").hide();
    }
	
	$("#selme").click(function () {
		if($(this).is(':checked')){
			setCookie("noprompt","1",365);
		}else{
			setCookie("noprompt","2",365);
		}
    });
}

var player = "mp3player_stu";

function loadMp3Player(mp3file,callback_p,callback_s){
	var playerInstance = jwplayer(player);
	playerInstance.setup({
		file: mp3file,
		height: 30,
		width: "100%",
		events: {
			onReady: function () {
				jwplayer(player).setVolume(100);
				setMplay3Carver();
				if(callback_p)	callback_p();
			},
			onPlay: function () {
				if(callback_s)	callback_s();
			}
		}
	});
}

function setMplay3Carver(){
	var top = $(window).scrollTop();
	$("#mp3player_stu_carver").css("top",$("#mp3player_stu").offset().top -top);
	$("#mp3player_stu_carver").css("left",$("#mp3player_stu").offset().left);
	$("#mp3player_stu_carver").width($("#mp3player_stu").width());
	$("#mp3player_stu_carver").height($("#mp3player_stu").height());
}

var scrolltimer1;
$(function() {
	initParam();
	u_c(classid,userid);
	var interv=self.setInterval(function(){
		u_c_c(classid,userid);
	},60000);
	$(window).scroll(function() { 
		if(scrolltimer1) clearInterval(scrolltimer1);
		var top = $(window).scrollTop();
		if(top<64) top = 64;
		scrolltimer1=setInterval(function(){
			$(".toolsBar").animate({top: top + "px" },300);
			$(".rightBox").animate({top: top + "px" },300);
			$(".stuView_all").animate({top: top + "px" },300);
			setMplay3Carver();
       },1000);
	});
	$("#setok").live("click",function(){
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.setStumic($("#selmic").val());
		$(window.parent.document).contents().find("#publishframe")[0].contentWindow.setStucam($("#selcam").val());
		setCookie("stu_selmic", $("#selmic").val(), 365);
		setCookie("stu_selcam", $("#selcam").val(), 365);
		$("#mysetModal").trigger('reveal:close');
	});
	
});
